package com.sinopec.ch34x.device.core.init

import android.content.Context
import android.hardware.usb.UsbManager
import cn.wch.ch34xuartdriver.CH34xUARTDriver
import com.sinopec.ch34x.device.core.config.Config

private const val ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION"

/**
 * lwj at 2023/5/18
 * 创建连接的设备
 */
internal fun ch34xUARTDriver(
    context: Context,
    usbManager: UsbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
): CH34xUARTDriver {
    return CH34xUARTDriver(usbManager, context, ACTION_USB_PERMISSION)
}

internal var ch34Driver: CH34xUARTDriver? = null


/**
 * lwj at 2023/5/18
 * 初始化driver
 * @return 是否成功
 */
internal fun initDriver(
    driver: CH34xUARTDriver
): Boolean {
    var result = true
    var retval = try {
        driver.ResumeUsbPermission()
    } catch (e: Exception) {
        -1
    }
    if (retval == 0) {
        //Resume usb device list
        retval = try {
            driver.ResumeUsbList()
        } catch (e: Exception) {
            -1
        }
        when (retval) {
            -1 -> {
                //////打开失败
                result = false
                try {
                    driver.CloseDevice()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
//                    throw RuntimeException("==========打开失败")
            }
            0 -> {
                if (driver.mDeviceConnection != null) {
                    ////对串口设备进行初始化操作
                    result = try {
                        driver.UartInit()
                    } catch (e: Exception) {
                        false
                    }
                } else {
                    result = false
                }
            }
            else -> {
                //没有权限
                result = false
//                    throw RuntimeException("==========没有权限")
            }
        }
    } else {
        //没有权限
        result = false
//            throw RuntimeException("==========没有权限")
    }
    return result
}


/**
 * lwj at 2023/5/22
 * 对外暴露 接口初始化
 */
fun initUsbDriver(context: Context, prams: Config) {
    if (ch34Driver == null) {
        ch34Driver = ch34xUARTDriver(context)
    }
    if (ch34Driver?.UsbFeatureSupported() == true) {
        try {
            val result = initDriver(ch34Driver!!)
//                    UsbEnsureLauncher.setResult(this, result)

            if (result) {
                //从intent中获取 config
                val config = prams ?: Config()
                ch34Driver?.SetConfig(
                    config.baudRate,
                    config.dataBit,
                    config.stopBit,
                    config.parity,
                    config.flowControl,
                )
            }
        } catch (e: Exception) {
//                    UsbEnsureLauncher.setResult(this, false)
        }
    }
}